package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查看地址列表
     * @return
     */
    public List<AddressBook> list() {
        Long userid = BaseContext.getCurrentId();
        List<AddressBook> list = addressBookMapper.list(userid);
        return list;
    }

    /**
     * 新增地址
     * @param addressBook
     */
    public void save(AddressBook addressBook) {
        Long userid = BaseContext.getCurrentId();
        addressBook.setUserId(userid);
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 修改默认地址
     * @param addressBook
     */
    @Transactional
    public void updatedefault(AddressBook addressBook) {
        //先将所有的地址改为 0（不是默认地址）
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsnotDefault(addressBook);

        //修改当前地址为 1（默认地址）
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 修改地址
     * @param addressBook
     */
    public void updateaddressBook(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 删除地址
     */
    public void delete(AddressBook addressBook) {
        addressBookMapper.delete(addressBook);
    }

    /**
     * 获取默认地址
     * @return
     */
    public AddressBook getDefaultAddressbook(AddressBook addressBook) {
        AddressBook addr = addressBookMapper.getDefaultAddressbook(addressBook);
        return addr;
    }
}
